<template>
    <div class="login-container">
        <!-- 导航 -->
        <van-nav-bar
            class="app-nav-bar"
            title="登录/注册"
            left-arrow
            @click-left="$router.back()"
        />
        <!-- 导航 -->
        <van-form @submit="onLogin" @failed="onFailed"
            :show-error="false" :show-error-message="false" 
            :submit-on-enter="false"  ref="form-validate" >
            <van-cell-group>
                <van-field
                    v-model="user.mobile"
                    name="mobile"
                    placeholder="请输入手机号"
                    icon-prefix="iconfont"
                    left-icon="shouji"
                    error-message-align="right"
                    :rules="formRules.mobile"
                />
                <van-field
                    v-model="user.code"
                    type="number"
                    name="code"
                    icon-prefix="iconfont"
                    left-icon="yanzhengma"
                    placeholder="请输入验证码"
                    error-message-align="right"
                    :rules="formRules.code"
                >
                    <template #button>
                        <van-count-down v-if="countDownisShow" :time="1000 * 60" format="ss s" @finish="countDownisShow = false" />
                        <van-button v-else :loading="sendSmsisLoading" class="send-btn" type="info" size="small" round @click.prevent="sendSms">验证码</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div class="vant-button-warp">
                <van-button class="vant-button" block type="primary">
                登录
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script>
import { login, sendSms } from '@/api/index'

// 定义一个refresh_token key常量
const TOKEN_KEY = 'user_local_token'
    export default {
        name:"login",
        data() {
            return {
                user:{
                    mobile:17090086870,
                    code:''
                },
                formRules:{
                    mobile:[
                        { required: true, message: '请输入手机号'},
                        { pattern:/^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误'}
                    ],
                    code:[
                        { required: true, message: '请输入验证码' },
                        { pattern:/\d{6}/, message: '验证码格式错误' }
                    ]
                },
                countDownisShow:false, //是否显示倒计时
                sendSmsisLoading:false, //判断发送短信按钮是否处于loading状态
            }
        },
        methods: {
            async onLogin(){
                this.$toast.loading({
                    message: '登录中...', //提示文字
                    forbidClick: true,  //禁止背景点击
                    duration: 0, //显示的时长，0为一直显示
                })
                //把发送短信按钮设置为loading状态
                this.sendSmsisLoading = true;
                // 1. 找到数据接口
                // 2. 封装请求函数 
                // 3. 请求调用接口
                try {
                    const res = await login(this.user);
                    if(res.status == 201){
                        // console.log(res);
                        this.$store.commit('setUser',res.data.data);
                        this.$toast.success("登录成功");

                        // 清除组件缓存
                        this.$store.commit('removeCachePage','layout');

                        this.$router.back();
                    }
                } catch (err) {
                    this.$toast.fail("登陆失败" + err.message)
                    // console.log(err.message)
                }
                // 4. 处理响应结果  
                // 无论是否发送短信验证码成功，都需要关闭发送短信按钮的loading状态
                this.sendSmsisLoading = false;
            },
            // 当表单验证失败的时候触发onFailed
            onFailed(e){
                this.$toast({
                    message:e.errors[0].message,
                    position:'top'
                })
            },
            async sendSms(){
                // 1. 校验手机号
                try {
                    await this.$refs['form-validate'].validate('mobile');
                    // 验证成功发送短信
                    const sendRet = await sendSms(this.user.mobile);
                    this.$toast({ message: '短信发送成功' , position:'top' })
                    console.log(sendRet)
                    // 2. 发送验证码，隐藏发送按钮，开启倒计时
                    this.countDownisShow = true;
                } catch (err) {
                    let message = '';
                    if(err && err.response && err.response.status === 429 ){
                        message = '发送数据太过频繁，请稍后再试'
                    }else if(err.name = 'mobile'){
                        message = err.message
                    }else{
                        message = '发生未知错误,请稍后重试'
                    }
                    this.$toast({
                        message,
                        position:'top'
                    })
                }
                // 2. 发送验证码，隐藏发送按钮，开启倒计时
                // 3. 倒计时结束，隐藏倒计时，显示发送按钮
            }
        },
        created() {

        }
    }
</script>

<style lang="less" scoped>
.login-container{
   .send-btn{
        width: 78px;
        height: 23px;
        background-color: #ededed;
        border: none;
        .van-button__content{
            .van-button__text{
                font-size: 11px;
                color: #666;
            }
        }   
    }
    .vant-button-warp{
        padding: 26px 16px;
        .vant-button{
            background-color: #6db4fb;
            border: none;
            .van-button__text{
                font-size: 12px;
            }
        }
    }
}
</style>